home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 August / August CD.bin / Shareware / Education / numericalmethods Folder / chap_2 / bisect.m < prev    next >
Encoding:
Text File  |  1994-06-05  |  838 b   |  37 lines  |  [MATF/MATL]

  1. function [c,yc,err,P] = bisect(f,a,b,delta)
  2. % [c,yc,err] = bisect(f,a,b,delta)
  3. % [c,yc,err,P] = bisect(f,a,b,delta)
  4. % The bisection method is used to locate a root.
  5. % f is the function, input.
  6. % a is the left endpoint, input.
  7. % b is the right endpoint, input.
  8. % delta is the tolerance, input.
  9. % c  is the root, output.
  10. % yc is the function value, output.
  11. % err is the error estimate for c, output.
  12. % P is the is the matrix of endpoint iterations, output.
  13. P = [a b];
  14. ya = feval(f,a);
  15. yb = feval(f,b);
  16. if ya*yb > 0, break, end
  17. max1 = 1 + round((log(b-a)-log(delta))/log(2));
  18. for k=1:max1,
  19.   c  = (a+b)/2;
  20.   yc = feval(f,c);
  21.   if  yc == 0,
  22.     a = c;
  23.     b = c;
  24.   elseif  yb*yc > 0,
  25.     b = c;
  26.     yb = yc;
  27.   else
  28.     a = c;
  29.     ya = yc;
  30.   end
  31.   P = [P;a b];
  32.   if b-a < delta, break, end
  33. end
  34. c  = (a+b)/2;
  35. yc = feval(f,c);
  36. err = abs(b-a)/2;
  37.